/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.prepare.asset;

import cn.ac.nercis.pes.common.constant.evaluation.EvaluationModule;
import cn.ac.nercis.pes.common.constant.project.FinishState;
import cn.ac.nercis.pes.community.component.controls.MenuListCell;
import cn.ac.nercis.pes.community.component.dialog.*;
import cn.ac.nercis.pes.community.component.spreadsheet.asset.AssetManageDocSheetView;
import cn.ac.nercis.pes.community.component.spreadsheet.asset.AssetSecurityDocSheetView;
import cn.ac.nercis.pes.community.manager.RealTimeSaveManager;
import cn.ac.nercis.pes.community.mapper.evaluation.AssetViewMapper;
import cn.ac.nercis.pes.community.mapper.evaluation.SecurityDocumentViewMapper;
import cn.ac.nercis.pes.community.model.vo.MenuVO;
import cn.ac.nercis.pes.community.utils.*;
import cn.ac.nercis.pes.model.dto.evaluation.asset.ManageDocumentDTO;
import cn.ac.nercis.pes.service.evaluation.AssetService;
import cn.ac.nercis.pes.service.evaluation.SecurityDocumentService;
import cn.ac.nercis.pes.service.project.SystemProcessService;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;
import java.util.List;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;

/**
 * 安全管理文档--系统资产管理控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class SecurityDocController extends BaseAssetController implements Initializable {

    @FXML
    private StackPane page;

    @FXML
    private Button saveButton;
    @FXML
    private Button tmpSaveButton;

    @FXML
    private ListView<MenuVO> menuList;
    @FXML
    private VBox securityDocBox;
    @FXML
    private VBox manageDocBox;

    @FXML
    private AssetSecurityDocSheetView securityDocSheetView;
    @FXML
    private AssetManageDocSheetView manageDocSheetView;

    private final AssetService assetService;
    private final SystemProcessService processService;
    private final SecurityDocumentService securityDocumentService;
    private final ExecutorService executor;
    private final RealTimeSaveManager realTimeSaveManager = new RealTimeSaveManager(this::realTimeSave);
    private String currentSystemId;

    public SecurityDocController() {
        this.assetService = SpringUtils.getBean(AssetService.class);
        this.securityDocumentService = SpringUtils.getBean(SecurityDocumentService.class);
        this.processService = SpringUtils.getBean(SystemProcessService.class);
        this.executor = SpringUtils.getBean(ExecutorService.class);
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        saveButton.setGraphic(IconUtils.getGlyph("save-button-icon","tool-button-icon"));
        tmpSaveButton.setGraphic(IconUtils.getGlyph("temp-save-button-icon","tool-button-icon"));
        this.initSaveListener(saveButton,tmpSaveButton);
        this.initializeMenu();
        GuiStore.applyQuickSave(this.page,this::onGlobalSave);
        realTimeSaveManager.listenerSheetChange(this.securityDocSheetView,this.manageDocSheetView);
    }

    @Override
    public void initializeData(String systemId) {
        LogUtils.info(log, "初始化系统资产-安全管理文档信息...");
        this.currentSystemId = systemId;
        this.securityDocSheetView.initialize(this.currentSystemId,this::onDeleteSecurityDoc);
        this.manageDocSheetView.initialize(this.currentSystemId,this::onDeleteManageDoc);
        this.menuList.getSelectionModel().select(0);
        this.querySecurityDoc();
        this.queryAsset();
    }

    @Override
    public void onGlobalSave() {
        LogUtils.info(log, "执行快捷保存操作...");
        batchSave(false,false);
    }



    @FXML
    public void onTmpSave(){
        LogUtils.info(log, "执行暂存操作...");
        this.batchSave(false,false);
    }

    @FXML
    public void onFinishSave(){
        LogUtils.info(log, "执行保存操作...");
        this.batchSave(false,true);
    }

    public void realTimeSave(){
        LogUtils.info(log, "执行即时保存操作...");
        this.batchSave(true,false);
    }

    @Override
    protected StackPane getPage() {
        return this.page;
    }

    @Override
    protected String getCurrentSystemId() {
        return this.currentSystemId;
    }

    @Override
    protected void onSuccessImport() {
        this.querySecurityDoc();
    }

    @Override
    protected SystemProcessService getProcessService() {
        return this.processService;
    }

    @Override
    protected ExecutorService getExecutorService() {
        return this.executor;
    }

    private void initializeMenu(){
        this.menuList.setCellFactory(cf->new MenuListCell());
        this.menuList.getSelectionModel()
                .selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> {
                    if(Objects.nonNull(newValue)){
                        loadContent(newValue);
                    }
                });
        this.menuList.getItems().add(new MenuVO(1,"securityDoc","安全管理文档",""));
        this.menuList.getItems().add(new MenuVO(2,"manageDoc","管理类文档",""));
    }

    private void loadContent(MenuVO menu){
        if(StringUtils.equals(menu.getCode(),"securityDoc")){
            this.manageDocBox.setVisible(false);
            this.securityDocBox.setVisible(true);
        } else if(StringUtils.equals(menu.getCode(),"manageDoc")){
            this.securityDocBox.setVisible(false);
            this.manageDocBox.setVisible(true);
        }
    }

    private void batchSave(boolean realTime,boolean finish){
        if(!this.securityDocSheetView.validate()){
            if(!realTime){
                AppUtils.showMessageDialog("以下标出的安全管理文档的必填信息不能为空",MessageType.WARN,this.page);
            }
            return;
        }
        if(!this.manageDocSheetView.validate()){
            if(!realTime){
                AppUtils.showMessageDialog("以下标出的管理类文档的必填信息不能为空",MessageType.WARN,this.page);
            }
            return;
        }
        var securityDocuments = securityDocSheetView.getModifyData().stream()
                .map(SecurityDocumentViewMapper.INSTANCE::toDTO)
                .toList();
        var manageDocuments = manageDocSheetView.getModifyData().stream()
                .map(AssetViewMapper.INSTANCE::toDTO)
                .toList();
        if (!realTime && CollectionUtils.isEmpty(securityDocuments) && CollectionUtils.isEmpty(manageDocuments)) {
            AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
            refreshFinishProcess(finish);
            return;
        }
        this.dataSaving.setValue(true);
        LogUtils.info(log, "批量保存系统资产-安全管理文档信息...");
        LogUtils.record(log, "请求数据，systemId：{},data:{}", this.currentSystemId, securityDocuments);
        CompletableFuture.supplyAsync(() -> this.securityDocumentService.batchSaveSecurityDocument(securityDocuments),this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    this.dataSaving.setValue(false);
                    if (res.isSuccess()) {
                        querySecurityDoc();
                        batchSaveManageDoc(realTime,manageDocuments, finish);
                    } else {
                        if(realTime){
                            log.error("即时保存系统资产-安全管理文档信息失败：{}",res.getMsg());
                        }else{
                            AppUtils.showMessageDialog(res.getMsg(),MessageType.FAIL,this.page);
                        }
                    }
                }))
                .exceptionally((ex) -> {
                    this.dataSaving.setValue(false);
                    log.error("批量保存系统资产-安全管理文档信息出错!", ex);
                    return null;
                });
    }

    private void batchSaveManageDoc(boolean realTime, List<ManageDocumentDTO> manageDocuments, boolean finish) {
        if (!realTime && CollectionUtils.isEmpty(manageDocuments)) {
            AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
            refreshFinishProcess(finish);
            return;
        }
        this.dataSaving.setValue(true);
        LogUtils.info(log, "批量保存系统资产-管理类文档信息...");
        LogUtils.record(log, "请求数据，systemId：{},data:{}", this.currentSystemId, manageDocuments);
        CompletableFuture.supplyAsync(() -> this.assetService.batchSaveManageDocument(this.currentSystemId, manageDocuments),this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    this.dataSaving.setValue(false);
                    if (res.isSuccess()) {
                        //更新表数据
                        this.queryAsset();
                        if(!realTime){
                            AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
                        }
                        refreshFinishProcess(finish);

                    } else {
                        if(realTime){
                            log.error("即时保存系统资产-管理类文档信息失败：{}",res.getMsg());
                        }else{
                            AppUtils.showMessageDialog(res.getMsg(),MessageType.FAIL,this.page);
                        }
                    }
                }))
                .exceptionally((ex) -> {
                    this.dataSaving.setValue(false);
                    log.error("批量保存系统资产-管理类文档信息出错!", ex);
                    return null;
                });
    }

    private void onDeleteSecurityDoc(Set<String> ids){
        LogUtils.info(log, "执行安全管理文档信息删除操作...");
        if(CollectionUtils.isEmpty(ids)){
            return;
        }
        AlertDialog alertDialog = AlertDialog.builder()
                .withMode(AlertMode.CONFIRM)
                .withType(AlertType.WARN)
                .withTitle("删除提示")
                .withContent("确认删除当前安全管理文档信息吗？")
                .withContainer(this.page)
                .build();
        alertDialog.show((confirm)->{
            if(!confirm){
                return;
            }
            deleteSecurityDoc(ids);
        });
    }

    private void deleteSecurityDoc(final Set<String> ids) {
        this.dataSaving.setValue(true);
        LogUtils.info(log, "删除安全管理文档信息...");
        LogUtils.record(log, "请求数据：{}", ids);
        CompletableFuture.supplyAsync(() -> this.securityDocumentService.batchDeleteSecurityDocument(ids),this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    this.dataSaving.setValue(false);
                    if (res.isSuccess()) {
                        //更新表数据
                        this.querySecurityDoc();
                        MessageDialog.builder()
                                .withContainer(this.page)
                                .withType(MessageType.SUCCESS).withMessage("删除成功")
                                .build().show();
                        refreshFinishProcess(false);
                    } else {
                        MessageDialog.builder()
                                .withContainer(this.page)
                                .withType(MessageType.FAIL).withMessage(res.getMsg())
                                .build().show();
                    }
                }))
                .exceptionally((ex) -> {
                    dataSaving.setValue(false);
                    log.error("删除安全管理文档信息出错!", ex);
                    return null;
                });
    }

    private void onDeleteManageDoc(Set<String> ids){
        LogUtils.info(log, "执行管理类文档信息删除操作...");
        if(CollectionUtils.isEmpty(ids)){
            return;
        }
        AlertDialog alertDialog = AlertDialog.builder()
                .withMode(AlertMode.CONFIRM)
                .withType(AlertType.WARN)
                .withTitle("删除提示")
                .withContent("确认删除当前管理类文档信息吗？")
                .withContainer(this.page)
                .build();
        alertDialog.show((confirm)->{
            if(!confirm){
                return;
            }
            checkDeleteAsset(ids);
        });
    }

    protected void querySecurityDoc() {
        LogUtils.info(log, "获取系统资产-安全管理文档信息...");
        LogUtils.record(log, "请求数据:{}", this.currentSystemId);
        CompletableFuture.supplyAsync(() -> this.securityDocumentService.findSecurityDocument(this.currentSystemId), this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    var data = res.stream()
                            .map(SecurityDocumentViewMapper.INSTANCE::toVO)
                            .toList();
                    this.securityDocSheetView.loadContent(data);
                }))
                .exceptionally((ex) -> {
                    log.error("获取系统资产-安全管理文档信息出错!", ex);
                    MessageDialog.builder()
                            .withContainer(this.page)
                            .withType(MessageType.FAIL).withMessage("加载数据表内容失败！")
                            .build().show();
                    return null;
                });
    }

    @Override
    protected AssetService getAssetService() {
        return this.assetService;
    }

    @Override
    protected void queryAsset() {
        LogUtils.info(log, "获取系统资产-管理类文档信息...");
        LogUtils.record(log, "请求数据:{}", this.currentSystemId);
        CompletableFuture.supplyAsync(() -> this.assetService.findManageDocument("", this.currentSystemId),this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    var data = res.stream()
                            .map(AssetViewMapper.INSTANCE::toVO)
                            .toList();
                    this.manageDocSheetView.loadContent(data);
                }))
                .exceptionally((ex) -> {
                    log.error("获取系统资产-管理类文档信息出错!", ex);
                    MessageDialog.builder()
                            .withContainer(this.page)
                            .withType(MessageType.FAIL).withMessage("加载数据表内容失败！")
                            .build().show();
                    return null;
                });
    }

    @Override
    protected void refreshFinishProcess(boolean finish){
        this.setSystemProcess(EvaluationModule.ASSET_SECURITY_DOC,
                finish ? FinishState.FINISH:FinishState.INCOMPLETE);
    }


}